import com.yao.servlet.IndexServlet;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

public class SpringApplication {

    private static int PORT = 8080;

    private static String CONTEX_PATH = "/haha";

    private static String SERVLET_NAME = "index";

    private static String MAPPING = "index";

    /**
     * tomcat8
     */
//    public static void main(String[] args) throws LifecycleException {
//        System.out.println("启动tomcat");
//
//        Tomcat tomcat = new Tomcat();
//
//        //设置端口
//        tomcat.setPort(PORT);
//
//        //此tomcat端口是否自动部署
//        tomcat.getHost().setAutoDeploy(false);
//
//        //创建一个web应用
//        StandardContext standardContext = new StandardContext();
//
//
//
//        //设置web应用程序的上下文地址
//        standardContext.setPath(CONTEX_PATH);
//        //添加web应用程序的监听
////        standardContext.addLifecycleListener(new Tomcat.FixContextListener());
//        tomcat.getServer().addLifecycleListener(new Tomcat.FixContextListener());
//        //将web应用程序添加到服务中
//        tomcat.getHost().addChild(standardContext);
//        //配置servlet和映射
//        tomcat.addServlet(CONTEX_PATH, SERVLET_NAME, new IndexServlet());
//        standardContext.addServletMappingDecoded("/"+MAPPING, SERVLET_NAME);
//        //启动tomcat
//        tomcat.start();
//        System.out.println("启动tomcat完毕");
//        //开启异步服务，接收请求
//        tomcat.getServer().await();
//    }


    /**
     * tomcat9
     * @param args
     */
    public static void main(String[] args) {
        Tomcat tomcat = new Tomcat();
//        String baseDir = Thread.currentThread().getContextClassLoader().getResource("").getPath();
//        //设置tomcat启动后的工作目录
//        tomcat.setBaseDir(baseDir);
        //设置端口
        tomcat.setPort(PORT);
        //获取执行器，并设置io协议
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        //设置端口
        connector.setPort(PORT);
        //设置执行器
        tomcat.setConnector(connector);


        StandardContext standardContext = new StandardContext();

        standardContext.setPath(CONTEX_PATH);
        //添加web应用程序的监听
        standardContext.addLifecycleListener(new Tomcat.FixContextListener());
//        tomcat.getServer().addLifecycleListener(new Tomcat.FixContextListener());
        //将web应用程序添加到服务中
        tomcat.getHost().addChild(standardContext);
        //配置servlet和映射
        tomcat.addServlet(CONTEX_PATH, SERVLET_NAME, new IndexServlet());
        standardContext.addServletMappingDecoded("/"+MAPPING, SERVLET_NAME);
        try {
            tomcat.start();
        } catch (LifecycleException e) {
            System.err.println("tomcat 启动失败");
        }
        //tomcat启动后，让其阻塞，不让当前线程结束，等待处理请求，
        System.out.println(tomcat.getServer().getCatalinaBase());
        tomcat.getServer().await();

    }
}